package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: reverseList2
 * @author: chanzhugang
 * @create: 2022/09/09 23:29
 */
public class ReverseList2 {

    /**
     * 206 反转链表
     * https://leetcode.cn/problems/reverse-linked-list/
     * 时间复杂度：O(n), n是链表的长度
     * 空间复杂度：O(n), 取决于递归调用的栈空间,最多n层
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 1-2-3-4-5
        // 递归
        if (head == null || head.next == null) {
            return head;
        }

        ListNode newHead = reverseList(head.next);
        // head = 4， head.next = 5
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}